package 数据结构.树.字典树;

import java.util.TreeMap;

/**
 * @author Veng Su 1344114844@qq.com
 * @date 2018/7/30 21:23
 */
public class Trie  {
    private class Node{
        public boolean isWord;
        public TreeMap<Character,Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            this.next=new TreeMap<>();
        }
        public Node(){
            this.isWord=false;
            this.next=new TreeMap<>();
        }
    }
    private Node root;
    private int size;

    public Trie(){
        root=new Node();
        size=0;
    }

    /**
     * 获取Trie中单词的数量
     * @return
     */
    public int getSize(){
        return size;
    }

    /**
     * 添加一个单词
     * 将string拆成字符，每次往下添加，看map中有没有这个字符，有就直接获取这个节点，没有就创建并获取
     * 到最后把单词的标志设置为true，只有当isword标志本来为false时才将size++
     * @param word
     */
    public void add(String word){
       Node cur=root;
        for (int i = 0; i < word.length(); i++) {
            char c =word.charAt(i);
            if (cur.next.get(c)==null){
                cur.next.put(c,new Node());
            }
            cur=cur.next.get(c);
        }
        if (!cur.isWord){
            cur.isWord=true;
            size++;
        }
    }

    /**
     * 查询单词word 是否在Trie中
     * @return
     */
    public boolean contains( String word){
        Node cur=root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c)==null){
                return false;
            }
            cur=cur.next.get(c);
        }
        return cur.isWord;
    }

    /**
     * 递归实现查询单词word是否在trie中
     * @param word
     * @return
     */
    boolean containword(String word){
        return contain(root,word);
    }
    private boolean contain(Node node,String word){
        if (word.equals("")){
            return false;
        }
        if (node.next.get(word.charAt(0))==null){
            return false;
        }
        if (word.length()>1){
            return contain(node.next.get(word.charAt(0)),word.substring(1));
        }else {
            return node.next.get(word.charAt(0)).isWord;
        }
    }

    /**
     * 是否存在prefix的前缀
     * @param prefix
     * @return
     */
    public boolean isPrefix(String prefix){
        Node cur =root;
        for (int i = 0; i < prefix.length(); i++) {
            char c=prefix.charAt(i);
            if (cur.next.get(c)==null)
                return false;
            cur=cur.next.get(c);
        }
        return true;
    }
}
